﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;

namespace QCOM_xml_parse
{
   public partial class Form1 : Form
   {
      
      public XmlDocument qcxml { get; }
      public List<string> CsvLog { get; private set; }
      public List<string> reclog { get; private set; }
      public List<string> matched { get; private set; }

      public List<string> checkBox_c { get; private set; }


      StringBuilder Tittle = new StringBuilder();
      StringBuilder Max = new StringBuilder();
      StringBuilder Min = new StringBuilder();
      StringBuilder Data = new StringBuilder();

      public Form1()
      {
         InitializeComponent();
         CommboxValue();
         this.comboBox1.SelectedIndex = 0;
         qcxml = new XmlDocument();

      }

      List<string> KeyTittle = new List<string>() {
         "Band", "Channel", "Ch_BW", "UL_Mod", "Start_RB",
         "Num_RB" , "Technology", "Mode", "Coding Scheme","UL_Desc","UL Desc","TimeOffset","Offset","Mask Area" ,"PA State","Frequency","LNA_State	"};

   

      private void button1_Click(object sender, EventArgs e)
      {
        
         checkBox_c = new List<string>();
         CsvLog = new List<string>();
         reclog = new List<string>();
         bool isFrist = true;
         try
         {
            DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
           
            foreach (var file in dir.GetFiles())
            {
               RST();
               Data.Append(file.FullName + ",");
               if (file.Extension.Contains("xml"))
               {
                 
                  qcxml.Load(file.FullName);
                  XmlElement ElementRoot = qcxml.DocumentElement;
                  string xpath = string.Empty;

                  switch (comboBox1.SelectedIndex)
                  {
                     case 0:                      
                        throw new Exception("请选择基节点！！");
                     case 1:
                        xpath = comboBox1.SelectedItem.ToString();
                        break;
                     case 2:
                        xpath = comboBox1.SelectedItem.ToString();
                        break;
                     case 3:
                        xpath = comboBox1.SelectedItem.ToString();
                        break;
                     default:
                        break;

                  }
                  XmlNodeList NodeList = ElementRoot.SelectNodes(xpath);

                  foreach (XmlNode Node in NodeList)
                  {

              
                     if (checkedListBox1.CheckedItems.Count != 0)
                     {
                                        
                        if (Tools.IsContains(Checkboxlist(checkedListBox1.CheckedItems), Node.InnerText))
                        {
                           reclog.AddRange(Run(Node.InnerText, Node));
                        }
                     }
                     else
                     {
                        checkBox_c.Add(Node.InnerText);
                     }
                  }
                  if (checkedListBox1.Items.Count == 0)
                  {
                     List<string> SS = checkBox_c.Distinct().ToList();
                     foreach (var item in SS)
                     {
                       checkedListBox1.Items.Add(item);
                     }

                     return;

                  }
                  if (checkedListBox1.CheckedItems.Count == 0)
                  {
                     textBox2.AppendText("选择需要整理的Tittle!\r\n");
                     return;
                  }
                  SplitREC(reclog, isFrist);
                  CsvAdd(isFrist);
                  isFrist = false;
                  textBox2.AppendText(file.Name + "\r\n");
               }
            }
            File.WriteAllLines($"{textBox1.Text}\\{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.csv", CsvLog);
            MessageBox.Show("Done!");
         }
         catch (Exception E)
         {
            MessageBox.Show(E.Message);
         }
        
      }
      private List<string> Run(string Name, XmlNode xmlNode)
      {
         List<string> Res = new List<string>();

         XmlNodeList TestDataSet = xmlNode.SelectNodes("parent::*/DataSetCollection/DataSet");
         foreach (XmlNode TestData in TestDataSet)
         {
            StringBuilder sb_Tittle = new StringBuilder();
            sb_Tittle.Append($"{Name}_");
            XmlNodeList TestDataInputs = TestData.SelectNodes("Inputs/DI");
            XmlNodeList TestDataOutputs = TestData.SelectNodes("Outputs/Result/DI");
            foreach (XmlNode Inputs in TestDataInputs)
            {
               string N = Inputs.SelectSingleNode("N").InnerText;
               if (KeyTittle.Contains(N))
               {
                  string V = Inputs.SelectSingleNode("V").InnerText;
                  sb_Tittle.Append($"{N}[{V}]_");
               }
            }
            foreach (XmlNode Outputs in TestDataOutputs)
            {
               string N = Outputs.SelectSingleNode("N").InnerText;
               string V = Outputs.SelectSingleNode("V").InnerText;
               XmlNode Max = Outputs.SelectSingleNode("parent::*/Limits/Max");
               XmlNode Min = Outputs.SelectSingleNode("parent::*/Limits/Min");
               string Tmax = Max == null ? "999" : Max.InnerText;
               string Tmin = Max == null ? "-999" : Max.InnerText;

               Res.Add($"{sb_Tittle}{N},{Tmax},{Tmin},{V}");
            }
         }
         return Res;
      }
      private void CsvAdd(bool isFrist)
      {
         if (isFrist)
         {
            CsvLog.Add(Tittle.ToString());
            CsvLog.Add(Max.ToString());
            CsvLog.Add(Min.ToString());
            CsvLog.Add(Data.ToString());
         }
         else
         {
            CsvLog.Add(Data.ToString());
         }
      }
      private void SplitREC(List<string> rec, bool isFrist = true)
      {

         foreach (string item in rec)
         {
            string[] Datas = item.Split(',');

            if (Tools.IsNumber(Datas[3]) && (!Datas[0].Contains("Count")))
            {

               if (isFrist)
               {
                  Tittle.Append($"{Datas[0]},");
                  Max.Append($"{Datas[1]},");
                  Min.Append($"{Datas[2]},");
                  Data.Append($"{Datas[3]},");
               }
               else
               {
                  Data.Append($"{Datas[3]},");
               }
            }
         }

      }

      private List<string> Checkboxlist(CheckedListBox.CheckedItemCollection box)
      {
         List<string> Checkbox = new List<string>();
         foreach (var item in box)
         {
            Checkbox.Add(item.ToString());
         }
         return Checkbox;
      }
      private void RST()
      {
         
         reclog.Clear();
         Data.Clear();
         Tittle.Clear();Tittle.Append("Item,");
         Max.Clear(); Max.Append("max,");
         Min.Clear(); Min.Append("min,");
      }

      private void button2_Click(object sender, EventArgs e)
      {
         checkedListBox1.Items.Clear();
         textBox2.Clear();
      }

      private void CommboxValue()
      {
         comboBox1.Items.Add("请先选择基节点!");
         comboBox1.Items.Add("/ROOT/TEST/TNAME");
         comboBox1.Items.Add("/source/TestCollection/Test/Name");
         comboBox1.Items.Add("/source/TestCollection/Test/ExtendedName");
         comboBox1.Items.Add("/source/TestCollection/Test/NodeName");
      }

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
      {
         checkedListBox1.Items.Clear();
         textBox2.Clear();
      }
   }
}
